package com.lcxw.hxzbim.netty.realization;

import com.alibaba.fastjson.JSONObject;
import com.lcxw.hxzbcommon.common.StringUtil;
import com.lcxw.hxzbim.activemq.Producer;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import com.lcxw.hxzbapi.entity.pojo.YwpdMember;
import com.lcxw.hxzbapi.service.YwpdMemberService;
import com.lcxw.hxzbcommon.common.RedisUtils;
import com.lcxw.hxzbcommon.common.RoomUtils;
import com.lcxw.hxzbim.netty.model.ReplyBody;
import com.lcxw.hxzbim.netty.model.SentBody;
import com.lcxw.hxzbim.netty.server.NettyServerHandler;

@Component
@Slf4j
public class ImRealization {

    @Resource
    RedisUtils redisUtils;

    @Resource
    YwpdMemberService ywpdMemberService;

    @Resource
    Producer producer;

    @Resource
    NettyServerHandler nettyServerHandler;

    //1、IM消息鉴权，使用userId和token鉴权。
    public ReplyBody checkToken(SentBody sentBody) {
        ReplyBody replyBody = new ReplyBody();

        String userId = sentBody.get("fromUserId");
        String token = sentBody.get("token");

        if (StringUtil.isEmpty(userId) || StringUtil.isEmpty(token)) {
            replyBody.setCode("500");
            replyBody.setMessage("fromUserId和token不能为空");
            return replyBody;
        }

        String key = sentBody.getKey();
        replyBody.setKey(key);
        //从redis中获取token，判断登录状态与token校验，登录成功的话redis中会保存token
        String redisKey = "uid:" + userId + ":token";
        if (!redisUtils.hasKey(redisKey)) {
            replyBody.setCode("500");
            replyBody.setMessage("用户未登录");
            return replyBody;
        }
        String tokenFromRedis = redisUtils.string_get(redisKey);
        if (StringUtil.isEmpty(tokenFromRedis) || !tokenFromRedis.equals(token)) {
            replyBody.setCode("500");
            replyBody.setMessage("用户在其他地方登录");
            return replyBody;
        }
        replyBody.setCode("200");
        replyBody.setMessage("鉴权成功");
        return replyBody;
    }

    //2、处理IM的请求，选择使用哪一路请求方式。
    public void dealRequest(SentBody sentBody) {
        String key = sentBody.getKey();
        switch (key) {
            case "10":
                imLoginRequest(sentBody);
                break;
            case "2":
                imBarrageRequest(sentBody);
                break;
            default:
                break;
        }
    }

    //3、用户进入直播间
    public void imLoginRequest(SentBody sentBody) {
        String userId = sentBody.get("fromUserId");
        YwpdMember ywpdMember = null;
        if (StringUtil.isEmpty(userId)) {
            log.error("userId为空");
            return;
        }
        try {
            ywpdMember = ywpdMemberService.selectYwpdMemberByUserId(Long.parseLong(userId));
            String nickName = ywpdMember.getNickName();

            String roomId = sentBody.get("roomId");
            String roomViewer_redisKey = RoomUtils.get_roomViewer_redisKey(roomId);
            Set<String> viewers = redisUtils.set_getMembers(roomViewer_redisKey);
            for (String viewer : viewers
            ) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("userId", viewer);
                jsonObject.put("messType", "1");
                jsonObject.put("nickName", nickName);
                String message = "欢迎" + nickName + "进入直播间";
                jsonObject.put("message", message);
                producer.topicSend(jsonObject);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("用户数据获取失败，数据库操作失败。");
        }

    }

    //4、用户进入直播间的响应，返回给netty响应客户端
    public void imLoginReply(JSONObject jsonObject) {

        String userId = jsonObject.getString("userId");
        ReplyBody replyBody = new ReplyBody();
        replyBody.setKey("2");
        replyBody.setCode("200");
        replyBody.setMessage("欢迎");
        Map<String, String> data = new HashMap<>();
        data.put("messType", jsonObject.getString("messType"));
        data.put("nickName", jsonObject.getString("nickName"));
        data.put("message", jsonObject.getString("message"));
        replyBody.putAll(data);
        nettyServerHandler.sendMessage(userId, replyBody);
    }

    //5、弹幕发送的请求处理
    private void imBarrageRequest(SentBody sentBody) {

    }

    //6、弹幕广播的消息构造，返回给netty响应客户端
    private void imBarrageReply() {

    }

}
